package org.shx.springboot.ollama.ai.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.shx.springboot.ollama.ai.service.DocumentService;
import org.shx.springboot.ollama.ai.domain.FileInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import org.springframework.ai.document.Document;

@RestController
@RequestMapping("/document")
@Tag(name = "Document相关接口")
public class DocumentController {

    @Resource
    private DocumentService documentService;

    @PostMapping("/upload")
    @Operation(summary = "上传txt、json、word、pdf等")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        List<String> documentIds = documentService.processDocument(file);
        return ResponseEntity.ok(documentIds.toString()) ;
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文件")
    public ResponseEntity<String> deleteFile(@RequestParam("documentIds") String documentIds) {
        documentService.deleteFile(documentIds);
        return ResponseEntity.ok("成功");
    }

    /**
     * 查询所有文件信息列表 本地文件
     */
    @GetMapping("/list")
    public List<FileInfo> getAllFiles() {
        return documentService.getAllFileInfos();
    }

    /*所有elk文档id*/
    @GetMapping("/all-ids")
    public ResponseEntity<List<String>> getAllDocumentIds() {
        return ResponseEntity.ok(documentService.getAllDocumentIds());
    }
    /*删除elk索引文档*/
    @DeleteMapping("/delAll")
    public ResponseEntity<Void> deleteAllDocuments() {
        documentService.deleteAllDocuments();
        //表示服务器成功处理了请求，但没有返回任何内容（响应体为空）。
        //通常用于删除操作成功（如 DELETE 请求）或不需要返回数据的更新操作。
        // 删除成功，无内容返回
//        return ResponseEntity.noContent().build();
        // 资源不存在
//        return ResponseEntity.notFound().build();
//        ResponseEntity.ok().build()：200 状态码，成功且可能包含响应体
//        ResponseEntity.notFound().build()：404 状态码，资源未找到
//        ResponseEntity.noContent().build()：204 状态码，成功但无内容
        return ResponseEntity.noContent().build();
    }
    /*elk*/
    @GetMapping("/search/text")
    public ResponseEntity<List<Document>> searchByText(
            @RequestParam("query") String query,
            @RequestParam(name = "topK", defaultValue = "5") int topK) {
        return ResponseEntity.ok(documentService.searchDocumentsByText(query, topK));
    }
    /*elk*/
    @GetMapping("/{id}")
    public ResponseEntity<Document> getById(@PathVariable("id")  String id) {
        return documentService.getDocumentById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}

